import { Component, OnInit } from '@angular/core';
import { load } from '@amap/amap-jsapi-loader';
import { WellService } from 'src/app/service/well.service';
import { getHoverContext } from '../../service/utils/hoverContext.js';
import { getWarningContext } from '../../service/utils/warningContext.js';
import { HoverModalComponent } from 'src/app/components/hover-modal/hover-modal.component.js';
//import * as echarts from 'echarts';
import * as echarts from 'echarts';
import 'echarts-extension-amap';
import { MapService } from 'src/app/service/map.service';
declare var AMap: any;

@Component({
    selector: 'app-visualization',
    templateUrl: './visualization.component.html',
    styleUrls: ['./visualization.component.scss'],
})
export class VisualizationComponent implements OnInit {
    t: any;
    title = 'myworld';
    chart: any;
    map: any; //地图
    normal = [];
    offline = [];
    warning = [];
    uninstalled = [];
    normalShow = [];
    offlineShow = [];
    warningShow = [];
    uninstalledShow = [];
    warningItem: any;
    wellData = [];
    radio: any;
    timer = null;
    clicklocation = [];
    distancemode = false;
    clicked = false;
    showDistance = false;
    distance: any;
    showStates = [false, false, false, false, false, false];
    isLoaded = false;
    satelliteObject: any;
    indexData: any;
    indexYear = new Date();
    showIndex = true;
    warnList:any;
    onlineDisplayFunction = (isInstalled?, isToShow?) => {
        var i;
        for (i = 0; i < 6; i++) {
            this.showStates[i] = false;
        }
        if (isInstalled === true) {
            this.showStates[0] = isToShow;
        } else {
            this.showStates[1] = isToShow;
        }
        if (isToShow === false) {
            //全显示
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = this.offline;
            this.uninstalledShow = this.uninstalled;
        } else {
            //仅显示
            if (isInstalled === true) {
                this.normalShow = this.normal;
                this.warningShow = this.warning;
                this.offlineShow = this.offline;
                this.uninstalledShow = [];
            } else {
                this.normalShow = [];
                this.warningShow = [];
                this.offlineShow = [];
                this.uninstalledShow = this.uninstalled;
            }
        }
    };
    changeLayer() {
        if (this.selectMapType == true) {
            console.log('hide');
            this.satelliteObject.hide();
        } else {
            console.log('show');
            this.satelliteObject.show();
        }
    }
    runDisplayFunction = (isRunning, isToShow) => {
        var i;
        for (i = 0; i < 6; i++) {
            this.showStates[i] = false;
        }
        if (isRunning === true) {
            this.showStates[2] = isToShow;
        } else {
            this.showStates[3] = isToShow;
        }
        if (isToShow === false) {
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = this.offline;
            this.uninstalledShow = this.uninstalled;
        } else {
            if (isRunning === true) {
                this.normalShow = this.normal;
                this.warningShow = this.warning;
                this.offlineShow = [];
                this.uninstalledShow = [];
            } else {
                this.normalShow = [];
                this.warningShow = [];
                this.offlineShow = this.offline;
                this.uninstalledShow = [];
            }
        }
    };
    warningDisplayFunction = (isWarning, isToShow) => {
        var i;
        for (i = 0; i < 6; i++) {
            this.showStates[i] = false;
        }
        if (isWarning === true) {
            this.showStates[4] = isToShow;
        } else {
            this.showStates[5] = isToShow;
        }
        if (isToShow === false) {
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = this.offline;
            this.uninstalledShow = this.uninstalled;
        } else {
            if (isWarning === true) {
                this.normalShow = [];
                this.warningShow = this.warning;
                this.offlineShow = [];
                this.uninstalledShow = [];
            } else {
                this.normalShow = this.normal;
                this.warningShow = [];
                this.offlineShow = [];
                this.uninstalledShow = [];
            }
        }
    };
    updateNumbers() {
        this.data.numbers.onlineNumber =
            this.normal.length + this.offline.length + this.warning.length;
        this.data.numbers.offlineNumber = this.uninstalled.length;
        this.data.numbers.runningNumber =
            this.normal.length + this.warning.length;
        this.data.numbers.shutNumber = this.offline.length;
        this.data.numbers.warningNumber = this.warning.length;
        this.data.numbers.normalNumber = this.normal.length;
    }
    data = {
        numbers: {
            onlineNumber: 0,
            offlineNumber: 0,
            runningNumber: 0,
            shutNumber: 0,
            warningNumber: 0,
            normalNumber: 0,
        },
        onlineDisplayFunction: this.onlineDisplayFunction,
        runningDisplayFunction: this.runDisplayFunction,
        warningDisplayFunction: this.warningDisplayFunction,
    };
    fetchData = async () => {
        console.log('刷新');
        let { data: res } = await this.wellService.fetchWellInfoByConfig({
            wellCode: null,
            wellId: null,
            wellName: null,
            address: null,
            applicantName: null,
        });
        // let { data: monitorList } = await fetchMonitorByConfig({})
        // const res = monitorList.map(item => {
        //   const well = wellList.find(it => it.id === item.wellId)
        //   return {
        //     ...well,
        //     ...item,
        //   }
        // })
        console.log('data', res);
        this.wellData = res;
        const genList = (e) => {
            return res.filter(e).map((item) => {
                return {
                    id: item.wellId,
                    name: item.wellName,
                    value: [item.longitude, item.latitude, item.flowCount],
                    applicantId: item.applicantId,
                };
            });
        };
        this.normal = genList((item) => item.status === 1001);
        this.warning = genList((item) => item.status === 4444);
        this.offline = genList((item) => item.status === 1003);
        this.uninstalled = genList((item) => item.status === 1002);
        this.data.numbers = {
            onlineNumber: 0,
            offlineNumber: 0,
            runningNumber: 0,
            shutNumber: 0,
            warningNumber: 0,
            normalNumber: 0,
        };
        this.updateNumbers();
        this.checkDisplay();
        this.setWell();
        getWarningContext().setPositionFunc(this.jumpTo);
        getWarningContext().setSelectedFunc(this.selectedItemByWarning);
        // getWarningContext().setData(res.filter(item => item.status === 4444))
    };
    selectedItemByWarning = (warningIt) => {
        // console.log('refresh')
        this.warningItem = warningIt;
        this.setWell();
    };
    jumpTo = (item) => {
        if (!this.chart) {
            return;
        }
        const amap = this.chart.getModel().getComponent('amap').getAMap();
        console.log('g', [item.latitude, item.longitude]);
        amap.setZoomAndCenter(14, [item.longitude, item.latitude], false, 300);
    };
    constructor(
        private wellService: WellService,
        private mapService: MapService
    ) {}
    selectMapType = true;
    option = [
        {
            label: '标准地图',
            value: true,
        },
        {
            label: '卫星地图',
            value: false,
        },
    ];
    checkDisplay() {
        if (this.showStates[0] === true) {
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = this.offline;
            this.uninstalledShow = [];
        } else if (this.showStates[1] === true) {
            this.normalShow = [];
            this.warningShow = [];
            this.offlineShow = [];
            this.uninstalledShow = this.uninstalled;
        } else if (this.showStates[2] === true) {
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = [];
            this.uninstalledShow = [];
        } else if (this.showStates[3] === true) {
            this.normalShow = [];
            this.warningShow = [];
            this.offlineShow = this.offline;
            this.uninstalledShow = [];
        } else if (this.showStates[4] === true) {
            this.normalShow = [];
            this.warningShow = this.warning;
            this.offlineShow = [];
            this.uninstalledShow = [];
        } else if (this.showStates[5] === true) {
            this.normalShow = this.normal;
            this.warningShow = [];
            this.offlineShow = [];
            this.uninstalledShow = [];
        } else {
            this.normalShow = this.normal;
            this.warningShow = this.warning;
            this.offlineShow = this.offline;
            this.uninstalledShow = this.uninstalled;
        }
    }
    async loadMap2() {
        this.chart = echarts.init(document.getElementById('map'));
        this.chart.on('mousemove', (e) => {
            console.log(e, this.wellData);
            getHoverContext().setPosition([
                e.event.event.clientX,
                e.event.event.clientY,
            ]);
            // console.log('find', store.state.wellList.find(item => item.well.id === e.data.id))
            getHoverContext().setData(
                this.wellData.find((item) => item.wellId === e.data.id)
            );
        });
        this.chart.on('mouseout', () => {
            getHoverContext().setPosition([-100, -100]);
            getHoverContext().setData(undefined);
        });

        this.chart.on('click', (e) => {
            //console.log(e.data.name);
            if (this.distancemode === true) {
                if (this.clicklocation.length === 0) {
                    this.clicklocation.push(e.data[0]);
                    this.clicklocation.push(e.data[1]);
                    this.clicklocation.push(e.data.name);
                    this.clicked = true;
                    this.showDistance = false;
                } else if (this.clicklocation.length === 3) {
                    this.clicklocation.push(e.data[0]);
                    this.clicklocation.push(e.data[1]);
                    this.clicklocation.push(e.data.name);
                    this.clicked = true;
                    this.distance = this.GetDistance(
                        this.clicklocation[4],
                        this.clicklocation[3],
                        this.clicklocation[1],
                        this.clicklocation[0]
                    );
                    console.log('距离为' + this.distance + 'km');
                    this.showDistance = true;
                    alert(
                        this.clicklocation[2] +
                            ' 至 ' +
                            this.clicklocation[5] +
                            '\n距离为 ' +
                            this.distance +
                            ' 千米'
                    );
                } else {
                    this.clicked = true;
                    this.showDistance = false;
                    this.clicklocation = [];
                    this.clicklocation.push(e.data[0]);
                    this.clicklocation.push(e.data[1]);
                    this.clicklocation.push(e.data.name);
                }
                console.log(this.clicklocation);
            }
        });

        const optionNew = {
            // amap component option
            amap: {
                // enable 3D mode
                viewMode: '3D',
                // initial options of AMap
                // See https://lbs.amap.com/api/javascript-api/reference/map#MapOption for details
                // initial map center [lng, lat]
                center: [105.227039, 37.607456],
                // initial map zoom
                zoom: 11,
                // whether the map and echarts automatically handles browser window resize to update itself.
                resizeEnable: true,
                // customized map style, see https://lbs.amap.com/dev/mapstyle/index for details
                mapStyle: 'amap://styles/macaron',
                // whether echarts layer should be rendered when the map is moving. Default is true.
                // if false, it will only be re-rendered after the map `moveend`.
                // It's better to set this option to false if data is large.
                renderOnMoving: true,
                // the zIndex of echarts layer for AMap, default value is 2000.
                // deprecated since v1.9.0, use `echartsLayerInteractive` instead.
                // echartsLayerZIndex: 2019,
                // whether echarts layer is interactive. Default value is true
                // supported since v1.9.0
                echartsLayerInteractive: true,
                // whether to enable large mode. Default value is false
                // supported since v1.9.0
                largeMode: false,
                // Note: Please DO NOT use the initial option `layers` to add Satellite/RoadNet/Other layers now.
                // There are some bugs about it, we can use `amap.add` instead.
                // Refer to the codes at the bottom.

                // More initial options...
            },
            // tooltip: {
            //   trigger: "item"
            // },
            animation: false,
            series: [
                {
                    name: '在线',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: [],
                    symbolSize: 27,
                    // symbolSize: function (val) {
                    //   return val[2] / 10;
                    // },
                    encode: {
                        value: 2,
                    },
                    showEffectOn: 'render', // 特效开启时机
                    rippleEffect: {
                        // 扩散特效
                        brushType: 'stroke',
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        // color: "rgba(255, 165, 0, 0.8)",
                        color: 'rgba(165, 255, 0, 0.8)',
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '报警',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: [],
                    symbolSize: 27,
                    // symbolSize: function (val) {
                    //   return val[2] / 10;
                    // },
                    encode: {
                        value: 2,
                    },
                    // showEffectOn: "render", // 特效开启时机
                    // rippleEffect: { // 扩散特效
                    //   brushType: "stroke"
                    // },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgba(255, 165, 0, 0.8)',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '离线',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: [],
                    symbolSize: 27,
                    // symbolSize: function (val) {
                    //   return val[2] / 10;
                    // },
                    encode: {
                        value: 2,
                    },
                    showEffectOn: 'emphasis', // 特效开启时机
                    rippleEffect: {
                        // 扩散特效
                        brushType: 'stroke',
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgba(165, 165, 165, 0.8)',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
            ],
        };
        this.chart.setOption(optionNew);
    }
    setWell = async () => {
        if (!this.chart) {
            await this.loadMap2();
            this.isLoaded = true;
            const amap = this.chart.getModel().getComponent('amap').getAMap();
            var satellite;
            satellite = new AMap.TileLayer.Satellite({
                map: amap,
            });
            this.satelliteObject = satellite;
            this.satelliteObject.hide();
        }
        const option = {
            animation: false,
            series: [
                {
                    name: '在线',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: this.normalShow,
                    symbolSize: 27,
                    // symbolSize: function (val) {
                    //   return val[2] / 10;
                    // },
                    encode: {
                        value: 2,
                    },
                    showEffectOn: 'emphasis', // 特效开启时机
                    rippleEffect: {
                        // 扩散特效
                        brushType: 'stroke',
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        // color: "rgba(255, 165, 0, 0.8)",
                        color: 'rgba(165, 255, 0, 0.8)',
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '报警',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: this.warningShow.filter((item) => {
                        if (this.warningItem) {
                            return (
                                this.warningItem.applicantId !==
                                item.applicantId
                            );
                        }
                        return true;
                    }),
                    showEffectOn: 'emphasis', // 特效开启时机
                    symbolSize: 27,
                    encode: {
                        value: 2,
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgba(255,110,118, 0.8)',
                        // color: 'blue',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '已选报警',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: this.warningShow.filter((item) => {
                        if (this.warningItem) {
                            return (
                                this.warningItem.applicantId ===
                                item.applicantId
                            );
                        }
                        return false;
                    }),
                    showEffectOn: 'render', // 特效开启时机
                    symbolSize: 27,
                    encode: {
                        value: 2,
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgba(255,110,118, 0.8)',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '停用',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: this.offlineShow,
                    symbolSize: 27,
                    encode: {
                        value: 2,
                    },
                    showEffectOn: 'emphasis', // 特效开启时机
                    rippleEffect: {
                        // 扩散特效
                        brushType: 'stroke',
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgba(165, 165, 165, 0.8)',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
                {
                    name: '未安装',
                    type: 'effectScatter', // 特效散点
                    coordinateSystem: 'amap',
                    data: this.uninstalledShow,
                    symbolSize: 27,
                    encode: {
                        value: 2,
                    },
                    showEffectOn: 'emphasis', // 特效开启时机
                    rippleEffect: {
                        // 扩散特效
                        brushType: 'stroke',
                    },
                    hoverAnimation: true,
                    label: {
                        formatter: '{b}',
                        position: 'right',
                        show: true,
                    },
                    itemStyle: {
                        color: 'rgb(194,20,229)',
                        // color: "rgba(165, 255, 0, 0.8)",
                        shadowBlur: 10,
                        shadowColor: '#333',
                    },
                    zlevel: 1,
                },
            ],
        };
        this.chart.setOption(option);
    };
    GetDistance(lat1, lng1, lat2, lng2) {
        var radLat1 = (lat1 * Math.PI) / 180.0;
        var radLat2 = (lat2 * Math.PI) / 180.0;
        var a = radLat1 - radLat2;
        var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
        var s =
            2 *
            Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(a / 2), 2) +
                        Math.cos(radLat1) *
                            Math.cos(radLat2) *
                            Math.pow(Math.sin(b / 2), 2)
                )
            );
        s = s * 6378.137; // EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }
    setupMap = () => {
        this.fetchData();
        this.t = setInterval(this.fetchData, 900000);
    };
    inDestory = () => {
        if (this.chart) {
            this.chart.dispose();
        }
        clearInterval(this.t);
    };
    getData = async () => {
        // let res = await fetchTarget({ year: i })
        const res = await this.mapService.fetchTargetInfo({
            year: this.indexYear.getFullYear(),
        });
        console.log(res);
        this.indexData = res;
    };
    changeIndexYear() {
        this.getData();
    }
    closeIndex() {
        this.showIndex = false;
    }
    async ngOnInit() {
        await this.setupMap();
        this.getWarn();
        this.getData();
    }
    ngOnDestroy() {
        clearInterval(this.timer);
        this.inDestory();
    }
    async getWarn(){
        const res = await this.mapService.fetchAlertApplicant()
      if (res) {
        this.warnList = res
      }
    }
    locate(e) {
        // const location = {
        //   longitude: e.longitude,
        //   latitude: e.latitude,
        // }
        // getWarningContext().setPosition(location)
        //console.log(e)
        getWarningContext().setSelected(e)
      }
}
